package com.example.ivideo_2211a.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.common.room.VideoFavorite
import com.example.ivideo_2211a.R
import com.example.ivideo_2211a.databinding.ItemHistoryVideoBinding

/**
 * 历史观看视频适配器
 */
class HistoryVideoAdapter(private val onVideoClick: (VideoFavorite) -> Unit = {}) : 
    ListAdapter<VideoFavorite, HistoryVideoAdapter.HistoryVideoViewHolder>(HistoryVideoDiffCallback()) {
    
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HistoryVideoViewHolder {
        val binding = ItemHistoryVideoBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return HistoryVideoViewHolder(binding, onVideoClick)
    }
    
    override fun onBindViewHolder(holder: HistoryVideoViewHolder, position: Int) {
        holder.bind(getItem(position))
    }
    
    class HistoryVideoViewHolder(
        private val binding: ItemHistoryVideoBinding,
        private val onVideoClick: (VideoFavorite) -> Unit
    ) : RecyclerView.ViewHolder(binding.root) {
        
        fun bind(video: VideoFavorite) {
            // 设置视频标题
            binding.historyVideoTitle.text = video.title
            
            // 设置点击事件
            binding.root.setOnClickListener {
                onVideoClick(video)
            }
            
            // 加载视频缩略图（这里使用小机器人图标作为占位符）
            Glide.with(binding.root.context)
                .load(video.avatar_url) // 使用小机器人图标
                .placeholder(R.drawable.ic_launcher_background)
                .error(R.drawable.ic_launcher_background)
                .into(binding.historyVideoThumbnail)
        }
    }
    
    class HistoryVideoDiffCallback : DiffUtil.ItemCallback<VideoFavorite>() {
        override fun areItemsTheSame(oldItem: VideoFavorite, newItem: VideoFavorite): Boolean {
            return oldItem.id == newItem.id
        }
        
        override fun areContentsTheSame(oldItem: VideoFavorite, newItem: VideoFavorite): Boolean {
            return oldItem == newItem
        }
    }
}